package ysq.weixin.client;


import ysq.weixin.util.SpringApplicationContextUtil;
import ysq.xyg.model.WxAccount;
import ysq.xyg.model.info.WxAccountInfo;
import ysq.xyg.service.WxAccountService;

import java.util.HashMap;
import java.util.Map;

/**
 * 缓存工具类；
 * 目前使用 服务器内存的方式；
 * 
 * 1、开发者可以根据自己的需求使用不同的缓存方式,比如memcached
 * 2、系统默认使用单个公众账号的缓存处理，如果有多个账号，请开发者自行处理
 * 
 */
public class WxMemoryCacheClient {
	private final static WxAccountService wxAccountService = (WxAccountService) SpringApplicationContextUtil.getBean("wxAccountService");
	//服务器内存的方式缓存wxAccountInfo
	private static Map<String,WxAccountInfo> wxAccountInfoMap = new HashMap<String,WxAccountInfo>();
	//删除
	public static void deleteSingleWxAccountInfo(){
		wxAccountInfoMap.clear();
	}
	//isUpdate：是否更新到数据库
	public static void addWxAccountInfo(WxAccountInfo account, boolean isUpdate){
		if(account != null){
			wxAccountInfoMap.put(account.getId(), account);
			if(isUpdate){
				WxAccount wxAccount= wxAccountService.selectByPrimaryKey(account.getId());
				wxAccount.setAccessToken(account.getAccessToken());
				wxAccount.setExpiresIn(account.getExpiresIn());
				wxAccount.setAccessTokenEndTime(account.getAccessTokenEndTime());
				wxAccount.setJsTicket(account.getJsTicket());
				wxAccount.setJsTicketEndTime(account.getJsTicketEndTime());
				wxAccountService.updateByPrimaryKey(wxAccount);
			}
		}
	}

	public static WxAccountInfo getWxAccountInfo(String account){
		return wxAccountInfoMap.get(account);
	}

	//获取唯一的公众号,如果需要多账号，请自行处理
	public static WxAccountInfo getSingleWxAccountInfo(String wxId){
		WxAccountInfo sigleAccount = wxAccountInfoMap.get(wxId);
		if(sigleAccount==null){
			sigleAccount=acceptWxAccountInfoForDatabases(wxId);
			addWxAccountInfo(sigleAccount,false);
		}
		return sigleAccount;
	}

	private static WxAccountInfo acceptWxAccountInfoForDatabases(String wxId){
		WxAccountInfo sigleAccount=new WxAccountInfo();
		WxAccount wxAccount= wxAccountService.selectByPrimaryKey(wxId);
		if(wxAccount !=null){
			sigleAccount.setId(wxAccount.getId());
			sigleAccount.setAppid(wxAccount.getAppid());
			sigleAccount.setAppsecret(wxAccount.getAppsecret());
			sigleAccount.setAccessToken(wxAccount.getAccessToken());
			sigleAccount.setAgentid(wxAccount.getAgentid());
			sigleAccount.setUrl(wxAccount.getUrl());
			sigleAccount.setAccessTokenEndTime(wxAccount.getAccessTokenEndTime());
			sigleAccount.setToken(wxAccount.getToken());
			sigleAccount.setName(wxAccount.getName());
			sigleAccount.setTemplateNum(wxAccount.getTemplateNum());
			sigleAccount.setTemplateId(wxAccount.getTemplateId());
			sigleAccount.setBaseURL(wxAccount.getBaseURL());
			sigleAccount.setJsTicket(wxAccount.getJsTicket());
			sigleAccount.setJsTicketEndTime(wxAccount.getJsTicketEndTime());
			sigleAccount.setPayKey(wxAccount.getPayKey());
			sigleAccount.setPayMchId(wxAccount.getPayMchId());
		}
		return sigleAccount;
	}

}


